<?php
namespace app\common\model;
use think\Db;
class User extends Base {
	protected $name = 'user';
	protected $resultSetType = 'collection';
	protected $pk = 'id';
	protected $createTime = 'ctime';
	protected $updateTime = '';

    protected $autoWriteTimestamp = true;

    public $dept = [
        0 => '前端',
        1 => '后端',
        2 => '产品经理',
        3 => '测试',
        4 => '运维'
    ];

    // 关联角色
    public function hasRoles()
    {
        return $this->belongsToMany('\app\home\model\Authgroup', '\app\home\model\AuthGroupAccess', 'group_id', 'uid');
    }
    //自动完成

    //关联查询
    public function dept(){
        return $this->hasOne('Dept','id')->field('id,name');
    }


    public function updata_check($data = []) {
		$rule = [
            ['name','require|max:25','用户名不能为空|名称最多不能超过8个字符'],
            ['mobile','require|max:25','手机号不能为空|名称最多不能超过15个字符'],
            ['password','require|max:25','密码不能为空|名称最多不能超过15个字符'],
            ['pid','require','上级id不能为空']
		];
	
		$validate = new Validate($rule);
		$result   = $validate->check($data);
		if(!$result){
			return ["code"=>1,"msg"=>$validate->getError()];
		}
	}


    /**
     * 查询单条数据
     * @param array $map 查询条件
     * @param bool $field 查询字段
     * @param array $append 追加数组
     * @return array 返回数组
     */
    public function getInfo($map = [], $field = true, $append = [])
    {
        $object = $this->where($map)->field($field)->find();
        if (!empty($object) && !empty($append))
        {
            $return = $object->append($append);
        } else
        {
            $return = $object;
        }
        return empty($return) ? [] : $return->toArray();
    }

    public function get_user_group($groupid,$field)
    {
        if (!empty($groupid)) {
            $object_list = //Db::name('user u')
                $this->alias('u')
                    ->join("hs_auth_group_access a","a.uid = u.id",'left')
                    ->join("hs_auth_group g","g.id = a.group_id",'left')
                    ->where(['a.group_id' => $groupid])
                    ->field($field)
                    ->group('u.id')
                    ->select();
        }
        $list = [];
        if (!empty($object_list))
        {
            foreach ($object_list as $item => $value)
            {
                if (!empty($append))
                {
                    $list[] = $value->append($append)->toArray();
                } else
                {
                    $list[] = $value->toArray();
                }
            }
        }
        return $list;

    }

    /**
     * 查询列表
     * @param array $map 查询条件
     * @param bool $field 查询字段
     * @param array $append 追加数据
     * @param string $order 排序
     * @param string $limit 分页
     * @return array 返回数据
     */
    public function getList($map = [], $field = true, $append = [], $order = '', $limit = '')
    {
        if (empty($order))
        {
            //默认按主键排序
            $order = [$this->primary_key => 'desc'];
        }
//        echo '<pre>';
//        var_dump($map,$field,$append,$order,$limit);die;
        if (!empty($limit))
        {
            $object_list = //Db::name('user u')
                $this->alias('u')
                ->join("hs_auth_group_access a","a.uid = u.id",'left')
                ->join("hs_auth_group g","g.id = a.group_id and g.deleted=0",'left')
                ->where($map)
                ->field($field)
                ->order($order)
                ->limit($limit)
                ->group('u.id')
                ->select();
        } else
        {
            $object_list = $this->alias('u')
                ->where($map)
                ->field($field)
                ->order($order)
                ->select();
        }
        $list = [];
        if (!empty($object_list))
        {
            foreach ($object_list as $item => $value)
            {
                if (!empty($append))
                {
                    $list[] = $value->append($append)->toArray();
                } else
                {
                    $list[] = $value->toArray();
                }
            }
        }
        return $list;
    }


    /**
     * 查询数据条数
     * @param array $map 查询条件
     * @return int|string
     */
    public function getCount($map = [])
    {
        return $this->alias('u')
                    //->join('dt_dept d','d.id=u.deptid')
                    ->where($map)
                    ->count();
    }



    /**
     * 查询单条数据返回对象
     * @param array $map 查询条件
     * @param bool $field 查询字段
     * @param array $append 追加器
     * @return object 返回对象
     */
    public function getObjInfo($map = [], $field = true, $append = [])
    {
        $object = $this->where($map)->field($field)->find();
        if (!empty($object) && !empty($append))
        {
            return $object->append($append);
        } else
        {
            return $object;
        }
    }


    /**
     * 批量保存数据
     * @param $data  数据
     * @return bool
     */
    public function batchSaveData($data)
    {
        $this->isUpdate(false)->saveAll($data);
        return true;
    }


    /**
     * 判断数据是否存在否则执行添加
     * @param $map 判断条件
     * @param array $extra_data 额外的数据
     * @param boole $is_strict 是否严格判断 true 时，如果数据存在，返回false
     * @return false|int|mixed
     */
    public function isExistElseAdd($map, $extra_data = [], $is_strict = false)
    {
        $info = $this->getInfoByMap($map);
        if (!empty($info))
        {
            if ($is_strict)
                return false;
            return $info[$this->primaryKey];
        } else
        {
            $data = array_merge($map, $extra_data);
            return $this->createData($data);
        }
    }

    //删除数据
    public function remove($map = [],$field = 'deleted'){
        $res = $this->where($map)->update([$field => time()]);
        return $res ? $res: false;
    }


    public function getCtimeAttr($time)
    {
        return date('Y-m-d',$time);
    }
}
